from flask import Flask, render_template, request, jsonify, session
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import os
import json
from collections import Counter
import re

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///comments.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    rating = db.Column(db.Integer, nullable=False)
    content = db.Column(db.String(200), nullable=False)
    category = db.Column(db.String(20), default='general')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    is_approved = db.Column(db.Boolean, default=True)

    def to_dict(self):
        return {
            'id': self.id,
            'rating': self.rating,
            'content': self.content,
            'category': self.category,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M'),
            'is_approved': self.is_approved
        }

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/comments', methods=['GET', 'POST'])
def handle_comments():
    if request.method == 'POST':
        data = request.json
        if not data or 'rating' not in data or 'content' not in data:
            return jsonify({'error': '缺少必要字段'}), 400
        
        if len(data['content']) > 200:
            return jsonify({'error': '评论内容超过200字限制'}), 400
        
        comment = Comment(
            rating=int(data['rating']),
            content=data['content'].strip(),
            category=data.get('category', 'general')
        )
        db.session.add(comment)
        db.session.commit()
        
        return jsonify({'message': '评论提交成功', 'comment': comment.to_dict()}), 201
    
    else:
        approved_comments = Comment.query.filter_by(is_approved=True).all()
        return jsonify([comment.to_dict() for comment in approved_comments])

@app.route('/api/stats')
def get_stats():
    comments = Comment.query.filter_by(is_approved=True).all()
    
    if not comments:
        return jsonify({
            'total': 0,
            'average_rating': 0,
            'rating_distribution': {},
            'keywords': [],
            'category_stats': {}
        })
    
    # 评分统计
    ratings = [c.rating for c in comments]
    rating_dist = dict(Counter(ratings))
    
    # 关键词提取
    all_text = ' '.join([c.content for c in comments])
    words = re.findall(r'\b[\u4e00-\u9fff]{2,}\b', all_text)
    keywords = [word for word, count in Counter(words).most_common(10)]
    
    # 分类统计
    category_stats = {}
    for category in ['剧情', '人物', '情感', '画面', '音乐', 'general']:
        count = len([c for c in comments if c.category == category])
        if count > 0:
            avg_rating = sum([c.rating for c in comments if c.category == category]) / count
            category_stats[category] = {'count': count, 'avg_rating': round(avg_rating, 1)}
    
    return jsonify({
        'total': len(comments),
        'average_rating': round(sum(ratings) / len(ratings), 1),
        'rating_distribution': rating_dist,
        'keywords': keywords,
        'category_stats': category_stats
    })

@app.route('/admin/login', methods=['POST'])
def admin_login():
    data = request.json
    if data.get('password') == 'admin123':
        session['admin'] = True
        return jsonify({'message': '登录成功'})
    return jsonify({'error': '密码错误'}), 401

@app.route('/admin/comments')
def admin_comments():
    if not session.get('admin'):
        return jsonify({'error': '未授权'}), 401
    
    comments = Comment.query.order_by(Comment.created_at.desc()).all()
    return jsonify([comment.to_dict() for comment in comments])

@app.route('/admin/comments/<int:comment_id>', methods=['DELETE'])
def delete_comment(comment_id):
    if not session.get('admin'):
        return jsonify({'error': '未授权'}), 401
    
    comment = Comment.query.get_or_404(comment_id)
    db.session.delete(comment)
    db.session.commit()
    return jsonify({'message': '删除成功'})

@app.route('/admin/logout', methods=['POST'])
def admin_logout():
    session.pop('admin', None)
    return jsonify({'message': '已退出'})

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True, host='0.0.0.0', port=5000)
